import json
from django.http import JsonResponse, HttpResponse
from django.views import View
from rest_framework.viewsets import ModelViewSet

from booktest.models import BookInfo
from booktest.serializers import BookInfoModelSerializer


class BookInfoViewSet(ModelViewSet):
    """定义书籍的视图集"""
    queryset = BookInfo.objects.all()  #　给视图集指定查询集
    serializer_class = BookInfoModelSerializer  #　指定序列化器


class BookAPIView(View):


    def get(self,request,pk):
        """GET    /books/<pk>/ 提供指定id的记录"""
        # 1.获取要查询的指定模型
        try:
            book = BookInfo.objects.get(pk = pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 2.把模型转换成json字典
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,
            "image": book.image.url if book.image else '',
        }

        return JsonResponse(book_dict)


    def put(self, request, pk):
        """put    /books/<pk>/ 修改指定id的记录"""
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)

        try:
            book = BookInfo.objects.get(pk = pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)

        # 此处详细的校验参数省略
        # 2.获取到与偶修改的指定模型
        # book = BookInfo()
        book.btitle = json_dict["btitle"]
        book.bpub_date = json_dict["bpub_date"]
        book.save()

        # 3.把已经保存的模型对象转换回json字典,并响应回去
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,
            "image": book.image.url if book.image else '',
        }

        return JsonResponse(book_dict, status=201)


    def delete(self,request,pk):
        """DELETE    /books/<pk>/ 删除指定id的记录"""
        # 获取要删除的指定模型
        try:
            book = BookInfo.objects.get(pk = pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        book.delete()

        return HttpResponse(status=204)


class BooksAPIView(View):
    """图书类视图"""
    # GET/books/  提供所有数据
    def get(self, request):
        # 1.获取所有书籍数据
        books = BookInfo.objects.all()
        # 2.把books中的一个一个模型换成一个一个的json字典
        book_list = []
        for book in books:
            book_dict = {
                "id": book.id,
                "btitle":book.btitle,
                "bpub_date":book.bpub_date,
                "bread": book.bread,
                "bcomment": book.bcomment,
                "image": book.image.url if book.image else '',
            }
            book_list.append(book_dict)

        # 因为json默认识别字典型的数据,所以提供book_list(列表)数据时需要提示为不安全的数据,否则会报错,(safe=False)
        return JsonResponse(book_list, safe=False)


    def post(self, request):
        """POST   /books/    新增一条数据"""
        # 1.获取请求体中的数据及类型的转换
        json_bytes = request.body
        json_str =json_bytes.decode()
        json_dict = json.loads(json_str)


        # 此处省略了校验环节
        # 2.把json字典转换成模型对象
        book = BookInfo()
        book.btitle = json_dict["btitle"]
        book.bpub_date = json_dict["bpub_date"]
        book.save()

        # 3.把已经保存的模型对象转换回json字典,并响应回去
        book_dict = {
            "id": book.id,
            "btitle": book.btitle,
            "bpub_date": book.bpub_date,
            "bread": book.bread,
            "bcomment": book.bcomment,
            "image": book.image.url if book.image else '',
        }

        return JsonResponse(book_dict)

